package mi.payment.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import mi.payment.MyApplication;
import mi.payment.ui.other.SettlementResultActivity;

/**
 * 缓存工具类
 *
 * @author longtao.li
 */
public final class SharedPreferencesUtil {

    public static final String PREFERENCE_FILE_NAME = "obj"; // 缓存文件名

    private SharedPreferencesUtil() {
        throw new AssertionError("create SharedPreferencesUtil instance is forbidden!");
    }

    /** 读取保存的对象 */
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T readObj(String key) {
        SharedPreferences spf = MyApplication.getInstance().getSharedPreferences(
                PREFERENCE_FILE_NAME, Context.MODE_PRIVATE);
        String replyBase64 = spf.getString(key, "");
        if (TextUtils.isEmpty(replyBase64)) {
            return null;
        }
        ObjectInputStream ois = null;
        try {
            // 读取字节
            byte[] base64 = Base64.decodeBase64(replyBase64.getBytes());
            // 封装到字节读取流
            ByteArrayInputStream inputStream = new ByteArrayInputStream(base64);
            // 封装到对象读取流
            ois = new ObjectInputStream(inputStream);
            // 读取对象
            return (T) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            close(ois);
        }
        return null;
    }

    /** 保存一个对象 */
    public static void saveObj(Serializable obj, String key) {
        SharedPreferences spf = MyApplication.getInstance().getSharedPreferences(
                PREFERENCE_FILE_NAME, Context.MODE_PRIVATE);
        ObjectOutputStream oos = null;
        try {
            // 创建字节输出流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // 创建对象输出流,封装字节流
            oos = new ObjectOutputStream(bos);
            // 将对象写入字节流
            oos.writeObject(obj);
            // 将字节流编码成base64的字符串
            String list_base64 = new String(Base64.encodeBase64(bos
                    .toByteArray()));
            Editor editor = spf.edit();
            editor.putString(key, list_base64);
            editor.apply();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(oos);
        }
    }

    /** 在UI线程调用SaveObject */
    public static void saveObjOnUIThread(final Serializable obj, final String key) {
        MyApplication.getInstance().post(new Runnable() {
            @Override
            public void run() {
                saveObj(obj, key);
            }
        });
    }

    /**
     * 清除某个key对应的缓存
     */
    public static void clearByKey(String key) {
        SharedPreferences pre = MyApplication.getInstance().getSharedPreferences(
                PREFERENCE_FILE_NAME, Context.MODE_PRIVATE);
        Editor editor = pre.edit();
        editor.putString(key, "");
        editor.apply();
    }

    /** 克隆一个对象 */
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T obj) {
        if (obj == null) {
            return null;
        }
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);

            return (T) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            close(oos);
            close(ois);
        }
        return null;
    }

    /** 关闭流 */
    private static void close(Closeable src) {
        if (src != null) {
            try {
                src.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
